<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
 body, html {
        height: 100%;
        margin: 0;
    }
 .header {
	 display: flex;
	 align-items: center;
	 justify-content: space-between;
	 padding: 10px 20px;
	 /* 			background-color:gainsboro; */
 }

 .logo {
	 height: 50px;
 }

 .title {
	 font-size: 24px;
	 font-weight: bold;
 }

 .links {
	 display: flex;
	 align-items: center;
 }

 .links el-link {
	 margin-left: 10px;
 }

 .user-info {
	 display: flex;
	 align-items: center;
 }

 .avatar {
	 margin-right: 10px;
 }

 .username a {
	 color: #333;
	 text-decoration: none;
 }
 /* 绿色点样式 */
 .green-point {
	 width: 10px;
	 height: 10px;
	 background-color: green;
	 border-radius: 50%;
	 margin-right: 10px;
	 display: inline-block;
 }

 /* 红色点样式 */
 .red-point {
	 width: 10px;
	 height: 10px;
	 background-color: red;
	 border-radius: 50%;
	 margin-right: 10px;
	 display: inline-block;
 }
 /* 橘黄色点样式 */
 .orange-point {
	 width: 10px;
	 height: 10px;
	 background-color: orange;
	 border-radius: 50%;
	 margin-right: 10px;
	 display: inline-block;
 }
    .container {
        display: flex;
        height: 100%;
    }
    .map-container {
        flex: 1; /* 地图容器占据剩余空间 */
    }
    #allmap {
        height: 400px;
        width: 100%;
        text-align: center;
    }
    .form-container {
        width: 40%;
        padding: 20px;
		padding-top:80px;
    }
	  #result {
	            position: fixed;
	            top: 80px;
	            left: 20px;
	            width: 300px;
	            height: 40px;
	            line-height: 40px;
	            text-align: center;
	            background: #fff;
	            box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
	            border-radius: 7px;
	            z-index: 99;
	        }
			 .point-container {
			        display: flex;
			        align-items: center; /* 垂直居中对齐 */
			    }
			    .point-container .blue-point,
			    .point-container .red-point {
			        margin-right: 10px;
			    }
				    .input-field {
				        max-width: 210px;
				    }
 .chat-container {
	 display: flex;
	 flex-direction: column;
	 height: 400px;
 }
 .messages {
	 flex: 1;
	 overflow-y: auto;
	 padding: 10px;
	 border: 1px solid #ebeef5;
 }
 .message {
	 display: flex;
	 align-items: center;
	 margin-bottom: 10px;
 }
 .message .avatar {
	 width: 40px;
	 height: 40px;
	 margin-right: 10px;
	 border-radius: 50%;
 }
 .message .content {
	 max-width: 60%;
	 padding: 10px;
	 border-radius: 5px;
	 background-color: #f2f2f2;
 }
 .message.sent .content {
	 margin-left: auto;
	 background-color: #cce5ff;
 }
 .message.sent .avatar {
	 order: 2;
	 margin-left: 10px;
 }
 .input-area {
	 display: flex;
	 align-items: center;
	 padding-top: 10px;
 }
 .input-area el-input {
	 flex: 1;
	 margin-right: 10px;
 }
 .order-dialog {
	 margin: 0 auto; /* 水平居中对齐 */
 }

 .order-dialog .el-dialog__body {
	 padding: 30px; /* 增加内边距 */
 }
 .button-group {
	 display: flex;
	 justify-content: center;
	 margin-top: 20px;
 }
					 
    </style>
    <script src="../js/vue.js"></script>
    <script src="../element-ui/lib/index.js"></script>
    <link rel="stylesheet" href="../element-ui/lib/theme-chalk/index.css">
    <script src="../js/axios-0.18.0.js"></script>
    <!-- 引入百度地图 API -->
    <script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=rXA8iQy9OhoIKkZEjWbO0xJR5c40gDcg"></script>
    <script src="https://api.map.baidu.com/api?v=1.0&amp;type=webgl&amp;ak=rXA8iQy9OhoIKkZEjWbO0xJR5c40gDcg"></script>
    <title>群星网约车</title>
	<link rel="icon" href="../image/carMR.png" type="image/png">
</head>
<body>
	<div id="app">
		<div class="header">
			<img class="logo" src="../image/carMR.png">
			<span class="title">群星网约车祝您一帆风顺</span>
			<div class="links">
				<el-link href="driverMain.html" target="_self" :underline="false" :disabled="true">主页&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
				<el-link href="orderDriverInfo.html" target="_self" :underline="false" :disabled="true">我的订单&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
				<el-link href="taxiInfo.html" target="_blank" :underline="false">群星简介&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
				<el-link href="driverInfo.html" target="_self" :underline="false" :disabled="true">个人中心&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
				&nbsp;&nbsp;&nbsp;&nbsp;
				<div v-if="driverStatus === '在线'">
					<div class="green-point"></div>
				</div>
				<div v-else-if="driverStatus === '离线'">
					<div class="red-point"></div>
				</div>
				<div v-else>
					<div class="orange-point"></div>
				</div>
				<el-select v-model="driverStatus" placeholder="选择司机状态" style="width: 120px;" :disabled="driverStatus === '接单中'">
					<el-option label="离线" value="离线"></el-option>
					<el-option label="在线" value="在线"></el-option>
					<el-option label="接单中" value="接单中"></el-option>
				</el-select>
			</div>
			<div class="user-info">
				<div>
					<el-avatar :src="avatar"></el-avatar>
				</div>
				&nbsp;&nbsp;&nbsp;&nbsp;
				<span class="username"><a id="uname" href="javascript:void(0)">{{ displayUsername }}</a></span>
				&nbsp;&nbsp;&nbsp;&nbsp;
				<el-link target="_blank" :underline="false" @click="exitInfo">退出系统</el-link>
				&nbsp;&nbsp;&nbsp;&nbsp;
			</div>
		</div>
    <div class="container">
        <div class="map-container">
            <div id="allmap"></div>
			 <!-- 隐藏输入框 -->
			<input type="hidden" id="searchInput" v-model="searchInput1" placeholder="输入地点名称">
			<input type="hidden" id="searchInput1" v-model="searchInput2" placeholder="输入地点名称">
        </div>
        <div class="form-container">
            <el-form ref="form" :model="form" label-width="80px">
<el-form-item label="起点" style="margin-bottom: 0;">
    <div class="point-container">
        <div class="green-point"></div> <!-- 绿色点表示起点 -->
        <el-input v-model="form.startPoint" class="input-field" readonly></el-input>
    </div>
</el-form-item>
<br>
<el-form-item label="终点" style="margin-bottom: 0;">
    <div class="point-container">
        <div class="red-point"></div> <!-- 红色点表示终点 -->
        <el-input v-model="form.endPoint" class="input-field" readonly></el-input>
    </div>
</el-form-item>
<br>
	<el-form-item label="路段距离" style="margin-bottom: 0; margin-left: 20px">
	<div class="point-container">
		<el-input v-model="distance" class="input-field" readonly></el-input>
	</div>
	</el-form-item>
				<br>
	<el-form-item label="到达时间" style="margin-bottom: 0; margin-left: 20px">
	<div class="point-container">
		<el-input v-model="time" class="input-field" readonly></el-input>
	</div>
	</el-form-item>
				<br>
	<el-button type="primary" @click="openChatDialog" style="margin-left: 35px">与乘客聊天</el-button>
    </el-form>
			<el-button v-if="!destinationReached" type="primary" style="position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);" @click="callPassenger">已到达乘客地点</el-button>
			<el-button v-else type="primary" style="position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);" @click="callPassengerArrived">已到达目的地</el-button>
			<el-dialog :visible.sync="chatDialogVisible" width="600px" :before-close="handleClose">
				<div class="chat-container">
					<div class="messages" ref="messages">
						<div v-for="msg in messages" :key="msg.id" :class="['message', { 'sent': msg.senderId === userIdStr }]">
							<img :src="msg.senderAvatar" class="avatar">
							<div class="content">
								<strong>{{ msg.senderName }}</strong>
								<p v-html="msg.content"></p>
							</div>
						</div>
					</div>
					<div class="input-area">
						<el-input v-model="inputMessage" placeholder="请输入消息"></el-input>
						<el-button type="primary" @click="sendMessage">发送</el-button>
						<el-upload
								class="upload-demo"
								action="/driver/drivers/common/upload"
								:on-success="handleUploadSuccess"
								:show-file-list="false">
							<el-button type="primary">上传图片</el-button>
						</el-upload>
						<emoji-picker @select="addEmoji"></emoji-picker>
					</div>
				</div>
			</el-dialog>
			<el-dialog :visible.sync="dialogVisible" title="发车验证" class="order-dialog">
				<div class="input-group">
					<el-input v-model="verificationCode" placeholder="请输入手机尾号四位" maxlength="4" show-word-limit clearable></el-input>
				</div>
				<div class="button-group">
					<el-button @click="arriveGo1" type="primary" plain>验证</el-button>
				</div>
			</el-dialog>
		</div>
		</div>
	</div>
    <div id="result">路线行驶规划</div>
    <script>
		// request拦截器，将用户token放入头中
		axios.interceptors.request.use(
				config => {
					let token = localStorage.getItem("token"); // 确保 token 正确存储在 localStorage 中
					if (token) {
						config.headers['token'] = token;
					}
					return config;
				},
				error => {
					console.log(error);
					return Promise.reject(error);
				}
		);
        new Vue({
            el: '#app',
            data: {
                form: {
                    startPoint: '',
                    endPoint: ''
                },
				time: '',
				distance: '',
				userId: '',
				durationAndDistanceReady: false,
				destinationReached: false,
				orderId: '',
				userName: '',
				websocket: null,
				dialogVisible: false,
				verificationCode: '' ,// 添加 verificationCode 数据项
				confirmInstance: null,
				searchInput1: '北京市西城区新疆阿达西',
				searchInput2: '北京市东城区东城区',
				driverStatus: '离线',
				avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png', // 默认头像链接
				chatDialogVisible: false,
				inputMessage: '',
				messages: [],
				userIdStr:'',
				phoneNum:''
            },
			created() {
				this.driverStatus = localStorage.getItem("driverStatus");
			},
            mounted() {
				var id=localStorage.getItem('userId');
				this.userIdStr=id;
				this.userId = parseInt(id, 10);
				this.userName = localStorage.getItem('userName');
				this.orderId=localStorage.getItem('orderId');
				this.initWebSocket();
				this.avatar = localStorage.getItem('pic');
				this.updateDriverStatus('2');
				/*
				if (this.userName === null) {
					this.$message.error('非法进入,请先登录');
					setTimeout(() => {
						window.location.href = "../html/login.html";
					}, 3000); // 延迟2秒（2000毫秒）执行
				} else {
					this.initMap();
				} */
				 this.initMap();
            },
            methods: {
/*				callPassengerArrived(){
					axios.post('/order/orders/callPassengerArrive?orderId='+this.orderId)
							.then(response=>{
								if(response.data.code==1){
									console.log("已发送订单信息");
								}
							});
					this.mapPosition();
					const data = {
						driverId: this.userId,
						location: this.searchInput2,
						time:this.calculateNewTime(this.time)
					};
					axios.put('/driver/driver-locations/updateLocationById',data)
							.then(response=>{
								if(response.data.code==1){
									console.log("修改位置成功");
								}
							});
					axios.put('/order/orders/updateStatus?orderId='+this.orderId)
							.then(response=>{
								if(response.data.code==1){
									console.log("订单未支付");
								}
							});
					this.$message.success('已发送订单信息....');
				},*/
				callPassengerArrived() {
					axios.post('/order/orders/callPassengerArrive?orderId=' + this.orderId)
							.then(response => {
								if (response.data.code == 1) {
									console.log("已发送订单信息");
									this.mapPosition();
									const data = {
										driverId: this.userId,
										location: this.searchInput2,
										time: this.calculateNewTime(this.time)
									};

									return axios.all([
										axios.put('/driver/driver-locations/updateLocationById', data),
										axios.put('/order/orders/updateStatus?orderId=' + this.orderId)
									]);
								} else {
									throw new Error('发送订单信息失败');
								}
							})
							.then(axios.spread((updateLocationResponse, updateStatusResponse) => {
								if (updateLocationResponse.data.code == 1) {
									console.log("修改位置成功");
								}

								if (updateStatusResponse.data.code == 1) {
									console.log("订单未支付");
								}

								this.$message.success('已成功发送订单信息....');
								setTimeout(() => {
									window.location.href = 'driverMain.html';
								}, 3000);

							}))
							.catch(error => {
								console.error("请求出错", error);
								this.$message.error('请求失败，请重试');
							});
				},
				arriveGo1(){
					// 获取手机号尾号后四位
					const lastFourDigits = this.phoneNum.slice(-4);
					// 获取用户输入的验证码
					const inputCode = this.verificationCode.trim();
					// 判断用户输入是否为四位数字
					if (/^\d{4}$/.test(inputCode)) {
						// 比较手机号尾号后四位与输入的验证码是否一致
						if (lastFourDigits === inputCode) {
							this.$message.success('发车啦~');
							axios.post('/order/orders/callPassenger1?orderId='+this.orderId)
									.then(response=>{
										if(response.data.code==1){
											console.log("响应顾客成功");
										}
									});
							this.dialogVisible = false; // 隐藏对话框
							this.plotNewRoute();
							this.destinationReached = true;

						} else {
							this.$message.error('手机尾号错误，请重新输入');
						}
					} else {
						this.$message.error('请输入四位数字'); // 提示用户输入四位数字
					}
				},
				initWebSocket() {
					//let clientId = Math.random().toString(36).substr(2);
					console.log(this.userId + "098user");
					const socketUrl = 'ws://localhost:10010/order/ws/driver/' + this.orderId.toString();
					if (typeof WebSocket === 'undefined') {
						this.$notify({
							title: '提示',
							message: '当前浏览器不支持 WebSocket，请使用最新版本的浏览器。',
							type: 'warning',
							duration: 0
						});
						return;
					}

					this.websocket = new WebSocket(socketUrl);

					this.websocket.onopen = () => {
						console.log('WebSocket 已连接');
					};

					this.websocket.onmessage = (msg) => {
						console.log('收到消息：', msg.data);
						const data = JSON.parse(msg.data);
						this.handleWebSocketMessage(data);
						console.log('你好000000000000000');
						this.$msgbox.close();
						this.confirmInstance.catch(() => {
							console.log('你好1000000000000000');
						});
					};

					this.websocket.onerror = (error) => {
						console.error('WebSocket 错误：', error);
						this.$notify({
							title: '错误',
							message: 'WebSocket 连接错误，请检查服务器状态。',
							type: 'error',
							duration: 0
						});
					};

					this.websocket.onclose = () => {
						console.log('WebSocket 已关闭');
					};
				},
				handleWebSocketMessage(data) {
					this.driverName=data.driverName;
					this.phoneNum=data.phoneNum;
					const audio = new Audio('../video/driver.mp3');
					audio.play();
					this.$notify({
						title: data.type === 3 ? '司机已到达' : '乘客已上车',
						message: '订单编号：'+data.orderId,
						type: 'info',
						duration: 0,
						onClick: () => {
							console.log('通知被点击');
							this.dialogVisible = true;
						}
					});
				},
				openChatDialog() {
					this.chatDialogVisible = true
					this.connectWebSocket()
				},
				connectWebSocket() {
					this.socket = new WebSocket(`ws://localhost:10010/order/ws/${this.orderId.toString()}/driver`)
					this.socket.onopen = () => {
						console.log('WebSocket连接成功')
					}
					this.socket.onmessage = (event) => {
						const message = JSON.parse(event.data)
						this.messages.push({ id: new Date().getTime(), ...message })
						this.$nextTick(() => {
							this.$refs.messages.scrollTop = this.$refs.messages.scrollHeight
						})
					}
					this.socket.onclose = () => {
						console.log('WebSocket连接关闭')
					}
					this.socket.onerror = (error) => {
						console.log('WebSocket错误', error)
					}
				},
				sendMessage() {
					if (this.inputMessage.trim() === '') return
					const message = {
						sessionId: this.userId.toString(),
						orderId: this.orderId.toString(),
						content: this.inputMessage,
						senderId: this.userId.toString(),
						senderName: this.userName,
						senderAvatar: this.avatar
					}
					this.socket.send(JSON.stringify(message))
					this.messages.push({ id: new Date().getTime(), ...message })
					this.inputMessage = ''
				},
				handleUploadSuccess(response, file) {
					const imageMessage = {
						id: new Date().getTime(),
						content: `<img src="${response.data}" />`,
						senderId: this.userId.toString(),
						senderName: this.userName,
						senderAvatar: this.avatar
					}
					this.socket.send(JSON.stringify(imageMessage))
					this.messages.push(imageMessage)
				},
				addEmoji(emoji) {
					this.inputMessage += emoji.native
				},
				handleClose(done) {
					this.socket.close()
					done()
				},
				async initMap() {
					try {
						const response = await axios.get('/driver/drivers/getLocation?driverId=' + this.userId);
						if (response.data.code == 1) {
							console.log("成功啦" + response.data.data);
							this.searchInput1 = response.data.data;
							this.searchInput2 = localStorage.getItem('departureLocation');

							// 等待 searchLocation 完成
							await this.searchLocation(this.searchInput1, 'people');
							await this.searchLocation(this.searchInput2, 'bass');

							this.form.startPoint=this.searchInput1;
							this.form.endPoint=this.searchInput2;
							// 从 localStorage 中取出四个值
							var peopleX = localStorage.getItem('peopleX');
							var peopleY = localStorage.getItem('peopleY');
							var bassX = localStorage.getItem('bassX');
							var bassY = localStorage.getItem('bassY');
							console.log(peopleX);
							console.log(peopleY);
							console.log(bassX);
							console.log(bassY);

							// 初始化地图
							this.map = new BMapGL.Map('allmap');
							var point = new BMapGL.Point(116.51397, 39.73517);
							this.map.centerAndZoom(point, 11);
							this.map.enableScrollWheelZoom(true);
							this.map.addControl(new BMap.NavigationControl());
							// 初始化LocalSearch
							this.local = new BMap.LocalSearch(this.map, {
								renderOptions: { map: this.map }
							});

							// 创建起点和终点的 BMapGL.Point 对象
							var start = new BMapGL.Point(parseFloat(peopleX), parseFloat(peopleY));
							var end = new BMapGL.Point(parseFloat(bassX), parseFloat(bassY));

							// 清除 localStorage 中的四个值
							localStorage.removeItem('peopleX');
							localStorage.removeItem('peopleY');
							localStorage.removeItem('bassX');
							localStorage.removeItem('bassY');

							// 创建驾车路线对象，并进行搜索
							var driving = new BMapGL.DrivingRoute(this.map, {
								renderOptions: {
									map: this.map,
									autoViewport: true,
									enableDragging: true,
								}
							});

							driving.search(start, end);
							var output = "驾车需要";
							var transit = new BMapGL.DrivingRoute(this.map, {
								renderOptions: { map: this.map },
								onSearchComplete: (results) => { // 使用箭头函数
									if (transit.getStatus() != BMAP_STATUS_SUCCESS) {
										return;
									}
									var plan = results.getPlan(0);
									output += plan.getDuration(true); // 获取时间
									this.time = plan.getDuration(true);
									output += "总路程为：";
									output += plan.getDistance(true); // 获取距离
									this.distance = plan.getDistance(true);
									console.log(this.time);
									console.log(this.distance);
									// 设置标识为true，表示duration和distance已经获取到了
									this.durationAndDistanceReady = true;
									const data = {
										orderId: this.orderId,
										durationDriver: this.time,
										distanceDriver: this.distance
									};
									axios.post('/order/orders/insertDT', data)
											.then(response => {
												if (response.data.code == 1) {
													console.log("成功啦12" + data);
												}
											});
								},
								onPolylinesSet: function () {
									setTimeout(function () { this.$message.success(output); }, 1000);
								}
							});
							transit.search(start, end);
						}
					} catch (error) {
						console.error('Error initializing map:', error);
					}
				},

				async plotNewRoute() {
					try {
						// 清除第一次路线规划
						this.map.clearOverlays();
						this.searchInput1 = localStorage.getItem('departureLocation');
						this.searchInput2 = localStorage.getItem('destinationLocation');

						// 等待 searchLocation 完成
						await this.searchLocation(this.searchInput1, 'newStart');
						await this.searchLocation(this.searchInput2, 'newEnd');

						this.form.startPoint=this.searchInput1;
						this.form.endPoint=this.searchInput2;
						// 从 localStorage 中取出四个值
						var newStartX = localStorage.getItem('newStartX');
						var newStartY = localStorage.getItem('newStartY');
						var newEndX = localStorage.getItem('newEndX');
						var newEndY = localStorage.getItem('newEndY');
						console.log(newStartX);
						console.log(newStartY);
						console.log(newEndX);
						console.log(newEndY);

						// 创建新的起点和终点的 BMapGL.Point 对象
						var newStart = new BMapGL.Point(parseFloat(newStartX), parseFloat(newStartY));
						var newEnd = new BMapGL.Point(parseFloat(newEndX), parseFloat(newEndY));

						// 清除 localStorage 中的四个值
						localStorage.removeItem('newStartX');
						localStorage.removeItem('newStartY');
						localStorage.removeItem('newEndX');
						localStorage.removeItem('newEndY');

						// 创建新的驾车路线对象，并进行搜索
						var newDriving = new BMapGL.DrivingRoute(this.map, {
							renderOptions: {
								map: this.map,
								autoViewport: true,
								enableDragging: true,
							}
						});

						newDriving.search(newStart, newEnd);
						var newOutput = "新的路线从起点到终点驾车需要";
						var newTransit = new BMapGL.DrivingRoute(this.map, {
							renderOptions: { map: this.map },
							onSearchComplete: (results) => { // 使用箭头函数
								if (newTransit.getStatus() != BMAP_STATUS_SUCCESS) {
									return;
								}
								var plan = results.getPlan(0);
								newOutput += plan.getDuration(true); // 获取时间
								this.time = plan.getDuration(true);
								newOutput += "总路程为：";
								newOutput += plan.getDistance(true); // 获取距离
								this.distance = plan.getDistance(true);
								console.log(this.newTime);
								console.log(this.newDistance);
								// 设置标识为true，表示新的duration和distance已经获取到了
								this.newDurationAndDistanceReady = true;
							},
							onPolylinesSet: function () {
								setTimeout(function () { this.$message.success(newOutput); }, 1000);
							}
						});
						newTransit.search(newStart, newEnd);
					} catch (error) {
						console.error('Error plotting new route:', error);
					}
				},
				searchLocation(address, keyPrefix) {
					return new Promise((resolve, reject) => {
						if (!address) return resolve();

						var geocoder = new BMap.Geocoder();
						geocoder.getPoint(address, (point) => {
							if (point) {
								var lng = point.lng; // 经度
								var lat = point.lat; // 纬度
								console.log("地点：" + address + " 的经度：" + lng + "，纬度：" + lat);
								localStorage.setItem(keyPrefix + 'X', lng);
								localStorage.setItem(keyPrefix + 'Y', lat);
								resolve(); // 成功时 resolve
							} else {
								console.log("无法获取地点：" + address + " 的经纬度坐标。");
								reject("Failed to get coordinates for " + address); // 失败时 reject
							}
						}, "衡阳市");
					});
				},
				mapPosition() {
					// 使用当前地图实例 this.map
					if (!this.map) {
						console.error("地图实例未初始化");
						return;
					}
					this.map.clearOverlays();
					// 添加搜索功能
					var local = new BMapGL.LocalSearch(this.map, {
						renderOptions: {
							map: this.map
						}
					});
					console.log("获取定位成功");
					var locationName = this.searchInput2;
					local.search(locationName);
				},
				calculateNewTime(time) {
					// 解析时间间隔
					let timeParts = time.match(/(\d+)小时(\d+)分钟/);
					if (!timeParts) {
						timeParts = time.match(/(\d+)分钟/);
					}

					let hoursToAdd = 0;
					let minutesToAdd = 0;

					if (timeParts[1]) {
						if (timeParts[2]) {
							// 包含小时和分钟的情况
							hoursToAdd = parseInt(timeParts[1]);
							minutesToAdd = parseInt(timeParts[2]);
						} else {
							// 只包含分钟的情况
							minutesToAdd = parseInt(timeParts[1]);
						}
					}

					// 获取当前时间
					const now = new Date();

					// 增加时间间隔
					now.setHours(now.getHours() + hoursToAdd);
					now.setMinutes(now.getMinutes() + minutesToAdd);

					// 格式化新时间
					const formattedTime =
							now.getFullYear() +
							"-" +
							String(now.getMonth() + 1).padStart(2, "0") +
							"-" +
							String(now.getDate()).padStart(2, "0") +
							" " +
							String(now.getHours()).padStart(2, "0") +
							":" +
							String(now.getMinutes()).padStart(2, "0") +
							":" +
							String(now.getSeconds()).padStart(2, "0");
					return formattedTime;
				},
				callPassenger(){
					const data = {
						driverId: this.userId,
						location: this.searchInput2,
						time:this.calculateNewTime(this.time)
					};
					axios.put('/driver/driver-locations/updateLocationById',data)
							.then(response=>{
								if(response.data.code==1){
									console.log("修改位置成功");
								}
							});
					axios.post('/order/orders/callPassenger?orderId='+this.orderId)
							.then(response=>{
								if(response.data.code==1){
									console.log("呼叫顾客成功");
								}
							});
					this.$message.success('呼叫顾客成功....');
				},
				exitInfo(){
					axios.put("/driver/drivers/exitStatus?driverId="+this.userId)
							.then(response=>{
								if(response.data.code==1){
									console.log("退出修改状态成功");
								}
							});
					localStorage.removeItem('userId');
					localStorage.removeItem('userName');
					window.location.href = "../html/login.html"; // 页面跳转
				},
				// 发送请求给后端更新司机状态
				updateDriverStatus(status) {
					axios.put('/driver/drivers/updateDriverStatus', {
						id: this.userId,
						status: status
					})
							.then(response => {
								console.log('更新司机状态成功:', response.data);
							})
							.catch(error => {
								console.error('更新司机状态失败:', error);
							});
				},
				// 监听司机状态变化
				onDriverStatusChange() {
					if (this.driverStatus === '接单中') {
						console.log('司机状态为接单中，不进行状态修改操作。');
						return; // 防止进一步操作
					}
					console.log('司机状态变为：', this.driverStatus);
					// 根据不同的司机状态发送请求给后端
					switch (this.driverStatus) {
						case '离线':
							// 发送请求告诉后端司机已经离线
							this.updateDriverStatus('3');
							break;
						case '在线':
							// 发送请求告诉后端司机已经上线
							this.updateDriverStatus('1');
							break;
						case '接单中':
							// 发送请求告诉后端司机正在接单
							this.updateDriverStatus('2');
							break;
						default:
							console.error('未知司机状态:', this.driverStatus);
							break;
					}
				},
            },
			computed: {
				displayUsername() {
					// 如果 userName 不为空，显示 userName；否则显示 "未登录"
					return this.userName ? this.userName : "未登录";
				}
			},
			watch: {
				// 监听司机状态变化
				driverStatus: 'onDriverStatusChange'
			},

        });
    </script>
	<script>
	</script>
</body>
</html>